import request from '@/utils/request'
import 'core-js/stable'

// 在ClassInfo.vue中修改studentApi定义
export const studentApi = {
  getAllStudents() {
    return request({
      url: '/spoc/api/students',
      method: 'get'
    }).then(res => {
      // 后端直接返回数组，所以不需要检查res.data
      if (!Array.isArray(res)) {
        console.error('API返回数据格式不正确:', res)
        return [] // 直接返回空数组
      }
      return res
    }).catch(error => {
      console.error('获取学生列表失败:', error)
      return [] // 出错时返回空数组
    })
  },
  searchStudents: (keyword) => {
    return request({
      url: '/spoc/api/students/search',
      method: 'get',
      params: { keyword }
    })
  },
  addStudentToClass: (classId, studentId) => {
    return request({
        url: `/spoc/api/students/batch-add-to-class?classId=${classId}`,
        method: 'post',
        data: [studentId]  // 单个学生也作为数组传递
    })
},

batchAddStudentsToClass: (classId, studentIds) => {
    return request({
        url: `/spoc/api/students/batch-add-to-class?classId=${classId}`,
        method: 'post',
        data: studentIds
    })
},
 // 从班级移除单个学生
removeStudentFromClass: (classId, studentId) => {
    return request({
        url: `/spoc/api/students/${classId}/students/${studentId}`,
        method: 'delete'
    })
},

// 批量从班级移除学生
batchRemoveStudentsFromClass: (classId, studentIds) => {
    return request({
        url: `/spoc/api/students/${classId}/students/batch`,
        method: 'delete',
        data: studentIds
    })
},
  getClassStudents: (classId) => {
    return request({
      url: `/api/classes/${classId}/students`,
      method: 'get'
    })
  },
   // 获取所有学生基本信息
  getAllStudents() {
    return request({
      url: '/spoc/api/students/all',
      method: 'get'
    })
  },
  
  // 根据ID获取学生详细信息
  getStudentDetailById(studentId) {
    return request({
      url: `/spoc/api/students/${studentId}/detail`,
      method: 'get'
    })
  },

// 修复的获取课程名称方法
  getCourseNamesByIds(courseIds) {
    return request({
      url: '/spoc/api/students/course-names',
      method: 'get',
      params: { courseIds: courseIds.join(',') } // 修改为逗号分隔的字符串
    })
  },

  getStudentClasses(studentId) {
  return request({
    url: `/api/student/classes/by-student/${studentId}`,
    method: 'get'
  })
},

getClassCourses(studentId, classId) {
  return request({
    url: `/api/student/classes/courses/${studentId}/${classId}`,
    method: 'get'
  })
},

  // 获取学生ID（增强错误处理）
  getStudentIdByUserId(userId) {
    return request({
      url: `/api/student/id/by-user/${userId}`,
      method: 'get',
      transformResponse: [
        function (data) {
          try {
            // 处理各种可能的响应格式
            if (!data) return { success: false, message: '无响应数据' }
            
            const parsed = typeof data === 'string' ? JSON.parse(data) : data
            
            // 处理直接返回ID的情况
            if (typeof parsed === 'number') {
              return { success: true, data: parsed }
            }
            
            // 处理标准响应格式
            const studentId = parsed.data || parsed.id || parsed.studentId
            return {
              success: !!studentId,
              data: studentId,
              message: parsed.message || (studentId ? '成功' : '未找到学生信息')
            }
          } catch (e) {
            console.error('解析学生ID失败:', e)
            return { success: false, error: e.message }
          }
        }
      ]
    })
  },
  // 获取班级详情
  getClassDetail(studentId, classId) {
    return request({
      url: `/api/student/classes/detail/${studentId}/${classId}`,
      method: 'get'
    })
  },

// students.js
// students.js
addCourseToStudent(studentId, courseId) {
  return request({
    url: `/api/student/classes/${studentId}/courses/${courseId}`,
    method: 'post',
    // 关键修改：禁用JSON自动转换
    transformResponse: [data => data],
    // 确保axios不尝试转换响应数据
    responseType: 'text'  // 明确指定期望文本响应
  })
},

  // 获取我的课程列表
  getMyCourses(studentId) {
    return request({
      url: `/api/student/courses/by-user/${studentId}`,
      method: 'get',
      transformResponse: [
        function(data) {
          try {
            const parsed = JSON.parse(data)
            // 处理不同数据结构
            if (Array.isArray(parsed)) {
              return parsed
            } else if (parsed.data && Array.isArray(parsed.data)) {
              return parsed.data
            } else if (parsed.list && Array.isArray(parsed.list)) {
              return parsed.list
            } else {
              const possibleArray = Object.values(parsed).find(v => Array.isArray(v))
              return possibleArray || []
            }
          } catch (error) {
            console.error('解析课程数据失败:', error)
            return []
          }
        }
      ]
    })
  },
  // 获取购物车课程（增强版）
  getStudentCartCourses(studentId) {
    return request({
      url: '/api/cart/student-courses',
      method: 'get',
      params: { studentId },
      transformResponse: [
        function(data) {
          try {
            const parsed = JSON.parse(data);
            // 处理不同数据结构
            if (Array.isArray(parsed)) {
              return {
                success: true,
                data: parsed.map(course => ({
                  ...course,
                  // 确保关键字段存在
                  id: course.id || course.courseId,
                  name: course.name || course.courseName,
                  price: course.price || course.couPrice,
                  originalPrice: course.originalPrice || course.couOriginalPrice,
                  coverUrl: course.coverUrl || course.couPic,
                  introduction: course.introduction || course.couIntro,
                  purchaseCount: course.purchaseCount || 0,
                  likeCount: course.likeCount || 0
                }))
              };
            }
            return { success: false, message: '数据格式不正确' };
          } catch (error) {
            console.error('解析购物车数据失败:', error);
            return { success: false, error: error.message };
          }
        }
      ]
    });
  },

  // 从购物车移除课程（增强版）
  removeCourseFromCart(courseId, studentId) {
    return request({
      url: `/api/cart/remove-course/${courseId}`,
      method: 'delete',
      params: { studentId },
      transformResponse: [
        function(data) {
          try {
            const parsed = JSON.parse(data);
            return {
              success: true,
              message: parsed.message || '课程已从购物车移除',
              removedCourseId: courseId
            };
          } catch (error) {
            return {
              success: false,
              message: '解析响应失败',
              error: error.message
            };
          }
        }
      ]
    });
  },

  createBatchOrder({ studentId, courseIds, totalAmount }) {
  return request({
    url: '/api/cart/batch-create-orders',
    method: 'post',
    data: { 
      studentId, 
      courseIds,
      totalAmount,
      createTime: new Date().toISOString()
    },
    // 添加更宽松的响应处理
    validateStatus: function (status) {
      // 接受200-299的状态码
      return status >= 200 && status < 300
    },
    transformResponse: [
      function(data) {
        try {
          const parsed = typeof data === 'string' ? JSON.parse(data) : data
          // 多种可能的成功判断方式
          const isSuccess = 
            parsed.success === true ||
            parsed.code === 200 ||
            parsed.status === 'success' ||
            (parsed.data && parsed.data.orderId)
            
          return {
            success: isSuccess,
            data: parsed.data || parsed,
            message: parsed.message || (isSuccess ? '订单创建成功' : '订单创建失败'),
            raw: parsed // 保留原始响应
          }
        } catch (error) {
          return {
            success: false,
            message: '解析响应失败',
            error: error.message
          }
        }
      }
    ]
  })
},

  // 批量删除购物车课程
  batchRemoveCartCourses({ studentId, courseIds }) {
    return request({
      url: '/api/cart/batch-remove-courses',
      method: 'delete',
      data: { studentId, courseIds },
      transformResponse: [
        function(data) {
          try {
            const parsed = JSON.parse(data);
            return {
              success: parsed.success !== false,
              message: parsed.message || '批量删除成功',
              removedCount: parsed.removedCount || courseIds.length
            };
          } catch (error) {
            return {
              success: false,
              message: '解析响应失败',
              error: error.message
            };
          }
        }
      ]
    });
  },

  // 批量创建订单
  createBatchOrder({ studentId, courseIds, totalAmount }) {
    return request({
      url: '/api/cart/batch-create-orders',
      method: 'post',
      data: { 
        studentId, 
        courseIds,
        totalAmount,
        createTime: new Date().toISOString()
      },
      transformResponse: [
        function(data) {
          try {
            const parsed = JSON.parse(data);
            return {
              success: parsed.success !== false,
              data: parsed.data,
              message: parsed.message || '订单创建成功'
            };
          } catch (error) {
            return {
              success: false,
              message: '解析响应失败',
              error: error.message
            };
          }
        }
      ]
    });
  },

}